<?php
/*
 * Leaderboard module
 * 
 * requires database.php
 */
 
 
//seconds required to refresh leaderboard table
//it is attempted to refresh everytime a user calls leaderboard page
define('leaderboard_refresh_time',600,true);//10mins

//leaderboard user limit
//maximum number of top players to be displayed in leaderboard
define('leaderboard_max_users',300,true);

	//functions for leaderboard
	function initializeLeaderboard(){
		$leaderboardLastrefreshed=time()-leaderboard_refresh_time;
		return insertNewSetting("leaderboardLF",$leaderboardLastrefreshed);
	}
	
	//refreshes the leaderboard 
	//interval to refresh is set in php.config
	//see leaderboard_refresh_time
	function refreshLeaderboard(){
		
		$leaderboard=table_leaderboard;
		$usertable=table_users;
		$max=leaderboard_max_users;
		
		//empty the table first
		$query="TRUNCATE TABLE `$leaderboard`;";
		$result=mysql_query($query);
		
		//copy records to leaderboard table with records sorted in desc order of scores
		$query="INSERT `$leaderboard` (`userid`, `score`, `loginname`, `nickname`, `movehistory`) " .
				"SELECT `id`,`score`,`loginname`,`nickname`,`movehistory` " .
				"FROM `$usertable` " .
				"ORDER BY `score` DESC " .
				"LIMIT $max;";
		
		$result=mysql_query($query);
		$time=time();
		
		//update last refresh time of leaderboard in settings
		updateSettings("leaderboardLF",$time);
		return $result;
	}
	

	//returns array of leaderboard records
	//returns array(userid, rank, loginname, nickname, score)
	function getLeaderboard(){
		global $settings;
		//check leaderboard and refresh if it is outdated.
		if ((time()-$settings['leaderboardLF'])>leaderboard_refresh_time){
			refreshLeaderboard();
		}
		$result=select("*",table_leaderboard,"","");
		return $result;
	}

if (!$settings['leaderboardLF']){
	$result=initializeLeaderboard();
}

?>
